<?php

require_once "I18N.php";

/**
 * 2010/10/21 
 * added html_gender_* & html_gendermore_* function
 *
 * 2011/12/15
 */  

  
$html_component_function_pointer = array(
  'h:list'             => 'html_list',
  'h:radio'            => 'html_radio',
  'h:checkbox'         => 'html_checkbox',
  'h:list'             => 'html_list',
  'h:option'           => 'html_list',
  'h:multiple_option'  => 'html_multiple_option',
  'h:label'            => 'html_label',
  'h:label_eip'        => 'html_label',  //edit in place
  
  'db:label'           =>  'html_db_label',
  'db:json'            =>  'html_db_json',
  
  'ny:label'           => 'html_yn_label',
  'ny:list'            => 'html_yn_list',
  'ny:radio'           => 'html_yn_radio',
  'ny:checkbox'        => 'html_yn_checkbox',
  'status:label'       => 'html_status_label',
  'status:list'        => 'html_status_list',
  'status:radio'       => 'html_status_radio',
  'gender:label'       => 'html_gender_label',
  'gender:list'        => 'html_gender_list',
  'gender:radio'       => 'html_gender_radio',
  'gendermore:label'   => 'html_gendermore_label',
  'gendermore:list'    => 'html_gendermore_list',
  'gendermore:radio'   => 'html_gendermore_radio',
  
  'boolean'            => 'html_boolean',
  'hidden'             => 'html_hidden',
  'text'               => 'html_text',
  'password'           => 'html_password',
  'textarea'           => 'html_textarea',
  'asis'               => 'html_asis',
  'ml_lookup'          => 'html_ml_lookup',
  'ml_mlookup'         => 'html_ml_mlookup',
);

function gen_html_component($type, $default, $name, $data_ptr, $extra_param){
	//error_log("gen_html_component $type, $default, $name");
	global $html_component_function_pointer;
	$extra_param = empty($extra_param) ? array():$extra_param;
	$function_name = isset($html_component_function_pointer[$type]) ? $html_component_function_pointer[$type] : ''; 
	if (function_exists($function_name)){
		return $function_name($default, $name, $data_ptr, $extra_param);
	} else {
		error_log('gen_html_component(): html component type '.$type.' not supported');
	}
	
	return '';
}

/*  
  } elsif ($type =~ /textarea/){
  	$ret_str = &gen_html_text($default, $name, $ptr, $type);
//	  $ret_str = &gen_html_ordered_list($default, $name, $ptr);
  } elsif ($type eq 'h:list_autocomplete'){
  	$ret_str = html_add_auto_complete(gen_html_hash_list($default, $name, $ptr));
  
  return $ret_str ;
}
*/
  

/************************************************************
 component
 ************************************************************/

function get_uninitialized_label($mode=null){
	switch ($mode){
	  case 'list': return '???'; # pull down, show ask people to select
	  case 'label': return '???';
	}
	return '-';
}

// Description:
//   pull down (single select)
//   $default_value: '', single value or a comma separated string
//   $h_data: associative array (pass by data)
//   $name  : name of html component, not used in label.
//   $extra_param: associative array of extra_parameter
function html_list($default_value, $name, $h_data, $extra_param=array()){
	// any css support added here?
	$extra_attribute = '';
	$uninit_default_value = '*NOTASSIGNED*'; # value that represent the value is not initialized
	
	if (is_null($extra_param)){
	  $extra_param = array('#DUMMY#' => 1); // force to be associative array	  
  } else {  	
  	if (array_key_exists('#SIZE#',     $extra_param)) $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MULTIPLE#', $extra_param)) $extra_attribute .= ' multiple';
  	if (array_key_exists('id',         $extra_param)) $extra_attribute .= ' id="'.$extra_param['id'].'"';
  	if (array_key_exists('#HEIGHT#',   $extra_param)) $extra_attribute .= ' height="'.$extra_param['#HEIGHT#'].'"';
  	if (array_key_exists('#UNINITIALIZED_VALUE#',   $extra_param)) $uninit_default_value = $extra_param['#UNINITIALIZED_VALUE#'];
  }
  
  $html_tag_name = array_key_exists('#MULTIPLE#', $extra_param) ? $name.'[]': $name;
  
	$a_result = array("<select name=\"$html_tag_name\"$extra_attribute>");
	
	if ( (empty($default_value) || $default_value == $uninit_default_value) &&  $uninit_default_value!=='*NOTASSIGNED*'){
		$a_default_value = array();
		$uninit_label = get_uninitialized_label('list');
		array_push($a_result, "<option value=\"$uninit_default_value\" selected>$uninit_label</option>"); 
	} else {
		if (array_key_exists('#MULTIPLE#', $extra_param)){
      $a_default_value = explode(',', $default_value);
    } else {
	    $a_default_value = array($default_value);
	  }
  }
  
  while ( list ($item_key, $item_value) = each($h_data)){
  	$selected = in_array($item_key, $a_default_value) ? ' selected' : '';
    array_push($a_result, "<option value=\"$item_key\"$selected>$item_value</option>"); 
  }
  array_push($a_result, '</select>');

  return implode("\n", $a_result);
}

// Descriptoin:
//   Alias for html_list()
function html_option($default_value, $name, $h_data, $extra_param=array()){
	return html_list($default_value, $name, $h_data, $extra_param);
}

//// obsolete as html_list support multiple selection & height
//function html_multiple_option($default_value, $name, $h_data, $extra_param=array()){
//	if (is_null($extra_param)){
//	  $extra_param = array('#MULTIPLE#' => 1, '#SIZE#' => 3);
//  } else {
//  	$extra_param['#MULTIPLE#'] = 1;
//  }
//	return html_list($default_value, $name, $h_data, $extra_param);
//}

function _escape_js_string($item){
  return str_replace("'","\'",$item);
}





/*
 * @param $a_data: 3 array element to represnet an item 
 */
function html_ml_lookupcb($default_value, $name, $a_data, $extra_param=array()){
	// any css support added here?
	$extra_attribute = '';
	if (is_null($extra_param)){
	  $extra_param = array('#DUMMY#' => 1); // force to be associative array	  
  } else {  	
  	if (array_key_exists('#SIZE#',     $extra_param)) $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MULTIPLE#', $extra_param)) $extra_attribute .= ' multiple="multiple"';
  	if (array_key_exists('id',         $extra_param)) $extra_attribute .= ' id="'.$extra_param['id'].'"';
  }
	$a_result = array("<select name=\"$name\"$extra_attribute></select>"); # use js to insert item
	
	if (array_key_exists('#MULTIPLE#', $extra_param)){
	  $a_default_value = explode(',', $default_value);
	} else {
		$a_default_value = array($default_value);
	}
 
	$a_result = array();
	$i=1;

	$width_css = isset($extra_param['width']) ? "style=\"float:left; width:".$extra_param['width']."\"" : '';
	
  #while ( list ($item_key, $top, $item_value) = each($a_data)){	
  $n_item = count($a_data);
  $counter = 0;
  for ($i=0; $i<$n_item; $i+=3){
    $item_key = $a_data[$i]; 
    $top      = $a_data[$i+1];
    $item_value = $a_data[$i+2];

    $checked = in_array($item_key, $a_default_value) ? ' checked' : '';
    $checkbox_id = "cb_{$name}_$counter"; $counter++;
    array_push($a_result, "<label for=\"$checkbox_id\" $width_css><input type=\"checkbox\" name=\"{$name}[]\" id=\"$checkbox_id\" value=\"$item_key\"$checked>$item_value</label><br>");
  }
  
  $container_start = '<div style="height: 100px; width:auto; float:left;overflow: auto; border: 5px solid rgb(238, 238, 238); background: none repeat scroll 0% 0% rgb(238, 238, 238); color: rgb(0, 0, 0); margin-bottom: 1.5em;">';
  $container_end   = '</div>'; 

  return $container_start.implode("\n", $a_result).$container_end;  
  
}



/*
 * @param $a_data: 3 array element to represnet an item 
 * NOTE: code of 'html_ml_lookup' and 'html_ml_mlookup' is quite similar. Merge later
 */
function html_ml_lookup($default_value, $name, $a_data, $extra_param=array()){
	// any css support added here?
	$extra_attribute = '';
	if (is_null($extra_param)){
	  $extra_param = array('#DUMMY#' => 1); // force to be associative array	  
  } else {  	
  	if (array_key_exists('#SIZE#',     $extra_param)) $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MULTIPLE#', $extra_param)) $extra_attribute .= ' multiple';
  	if (array_key_exists('id',         $extra_param)) $extra_attribute .= ' id="'.$extra_param['id'].'"';
  	#if (array_key_exists('#HEIGHT#',   $extra_param)) $extra_attribute .= ' height="'.$extra_param['#HEIGHT#'].'"';
  }
	$a_result = array("<select id=\"$name\" name=\"$name\"$extra_attribute></select>"); # use js to insert item
	
	if (array_key_exists('#MULTIPLE#', $extra_param)){
	  $a_default_value = explode(',', $default_value);
	} else {
		$a_default_value = array($default_value);
	}

  $js_var_name = 'ml_lookup_'.$name;
  $js_var_name = preg_replace('/(\[\])$/',  '', $js_var_name);

  $a_js_data = array();
  foreach ($a_data as $data){
  	array_push($a_js_data, str_replace("'","\'",$data));
  }
  $js_data = implode("','", $a_js_data);
  
  $js_array = "var $js_var_name = ['".$js_data."'];\n";
  
  $js = "<script language=\"JavaScript\"><!--
$js_array
new ml_lookup('$name' ,$js_var_name, '$default_value');
//--></script>
";
  array_push($a_result, $js);
  return implode("\n", $a_result);

}

/*
 * @param $a_data: 3 array element to represnet an item 
 */
function html_ml_mlookup($default_value, $name, $a_data, $extra_param=array()){
	// any css support added here?
	$prop_collapse = 'false'; 
	$prop_cbLeafOnly = 'false';
	
	$extra_attribute = '';
	if (is_null($extra_param)){
	  $extra_param = array('#DUMMY#' => 1); // force to be associative array	  
  } else {  	
  	if (array_key_exists('#SIZE#',     $extra_param)) $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MULTIPLE#', $extra_param)) $extra_attribute .= ' multiple';
  	if (array_key_exists('id',         $extra_param)) $extra_attribute .= ' id="'.$extra_param['id'].'"';
  	if (array_key_exists('#COLLAPSE#', $extra_param)) {
  		$prop_collapse = $extra_param['#COLLAPSE#'] == 1 ? 'true' : 'false' ;
  	}	
  	if (array_key_exists('#CBLEAFONLY#', $extra_param)) {
  		$prop_cbLeafOnly = $extra_param['#CBLEAFONLY#'] == 1 ? 'true' : 'false' ;
  	}	  	
  }
	
	if (array_key_exists('#MULTIPLE#', $extra_param)){
	  $a_default_value = explode(',', $default_value);
	} else {
		$a_default_value = array($default_value);
	}

  
  $html_element_id = 'ml_mlookup'.$name; // the [] is append inside JS
  $js_var_name     = 'ml_mlookup_'.$name;
	
  $a_result = array("<ul class=\"checkboxTree\" id=\"BOX_$html_element_id\"></ul>"); # use js to insert item
  
  $a_js_data = array();
  foreach ($a_data as $data){
  	array_push($a_js_data, str_replace("'","\'",$data));   #  ' is escaped
  }
  $js_data = implode("','", $a_js_data);
  
  
  $js_array = "var $js_var_name = ['".$js_data."'];\n";
 
   $default = 1;

  $js = "<script language=\"JavaScript\"><!--
$js_array
$(document).ready(function() {
   $('#BOX_$html_element_id').mlm_lookup({data:$js_var_name, name:'$name', selected:'$default_value', multiple:true, collapse:$prop_collapse, cbLeafOnly:$prop_cbLeafOnly});
});
//--></script>
";
  array_push($a_result, $js);
  return implode("\n", $a_result); 
}





// Description: 
//   show selected value 'label', parameter refer to html_list()
//   support multiple default value, separate by ','
// Note:
//   pass by reference for h_data ??? bugme...
//
function html_label($default_value, $name, $h_data, $extra_param=array()){
	
	$uninit_default_value = '*NOTASSIGNED*';
	if (array_key_exists('#UNINITIALIZED_VALUE#',   $extra_param)) $uninit_default_value = $extra_param['#UNINITIALIZED_VALUE#'];

  if ( is_null($default_value) || $default_value == $uninit_default_value || strcmp($default_value, '')==0 ){
  	if ( $uninit_default_value != '*NOTASSIGNED*' ){
  	  return get_uninitialized_label('label');
  	} else {
  	  return '';//$h_data[$name]; /// change of implementation	
  	}
  } 
  
  $a_default_value = explode(',', $default_value);
  if (count($a_default_value)==1){ // shortcut for 1 default value
  	if (isset($a_default_value[0]) && isset($h_data[$a_default_value[0]]) ){
  	  return $h_data[$a_default_value[0]];    
  	}
  	return '';
  } 
  
	$a_result = array();

  foreach ($a_default_value as $temp_dv){
  	if (array_key_exists($temp_dv, $h_data)){
  		array_push($a_result, $h_data[$temp_dv]);
  	}
  }

  return implode(', ', $a_result);
}

// Description: 
//   show radio html form component, parameter refer to html_list()
function html_radio($default_value, $name, $h_data, $extra_param=array()){
	$a_result=array();
  while ( list ($item_key, $item_value) = each($h_data)){	
    $checked = strcmp($default_value,$item_key) == 0 ? ' checked' : '';
    array_push($a_result, "<input id=\"lbl_$name$item_key\" type=\"radio\" name=\"$name\" value=\"$item_key\"$checked><label for=\"lbl_$name$item_key\">$item_value</label>\n");
  }
  
  return implode("\n", $a_result);
}

/* Description: 
 *   show checkbox html form component, parameter refer to html_list(),
 *   support multiple default value, separate by ','
 */
function html_checkbox($default_value, $name, $h_data, $extra_param=array()){
  $a_default_value = $default_value == '' ? array() : explode(',', $default_value);  
	$a_result = array();
	$i=1;

	$width_css = isset($extra_param['width']) ? "style=\"float:left; width:".$extra_param['width']."\"" : '';
	$overall_width = isset($extra_param['overall_width']) ? $extra_param['overall_width'] : '';
	
	
  while ( list ($item_key, $item_value) = each($h_data)){	
    $checked = in_array($item_key, $a_default_value) ? ' checked' : '';
    $checkbox_id = "cb_{$name}_$i"; $i++;
    array_push($a_result, "<label for=\"$checkbox_id\" $width_css><input type=\"checkbox\" name=\"{$name}[]\" id=\"$checkbox_id\" value=\"$item_key\"$checked>$item_value</label>");
  }
  
  if ($overall_width != ''){
    return '<div style="width:'.$overall_width.'">'.implode("\n", $a_result).'</div>';
  }
  
  return implode("\n", $a_result);
}

// description:
//   helper function for html_yn_list & etc
//
function _get_yn_array_by_default_value($default_value){
	if (preg_match('/^y|n$/', $default_value)){
		return array('y' => locale_string('Yes'), 'n' => locale_string('No'));
	} else if (preg_match('/^Y|N$/', $default_value)){
		return array('Y' => locale_string('Yes'), 'N' => locale_string('No'));
	}
	
	// prefered, use integer
	return array('0' => locale_string('No'), '1' => locale_string('Yes'), );
}

/* description:
 *   helper function for html_status_list & etc
 */
function _get_status_array_by_default_value($default_value){
	// prefered, use integer
	return array('0' => locale_string('Deleted'), '1' => locale_string('Show'), '2' => locale_string('Offline'));
}


/* description:
 *   helper function for html_status_list & etc
 */
function _get_gender_array_by_default_value($default_value){
	// prefered, use integer
	return array( '1' => locale_string('M'), '2' => locale_string('F'), '3' => locale_string('Not Specified'));
}

/* description:
 *   helper function for html_status_list & etc
 */
function _get_gendermore_array_by_default_value($default_value){
	// prefered, use integer
	return array( '0' => locale_string('Not input'), '1' => locale_string('M'), '2' => locale_string('F'), '3' => locale_string('Not Specified'));
}




// description:
//    for display field with enum('Y', 'N'), enum('y', 'n')  or 0=n,1=y
//    $h_data_dummy is dummy (will not be used) in this case, use internal value is fine
function html_yn_list($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_yn_array_by_default_value($default_value);
	return html_list($default_value, $name, $h_data, $extra_param);
}


// Description:
//   refer to html_yn_list()
function html_yn_radio($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_yn_array_by_default_value($default_value);
	return html_radio($default_value, $name, $h_data, $extra_param);
}

// Description:
//   refer to html_yn_list()
function html_yn_label($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_yn_array_by_default_value($default_value);
	return html_label($default_value, $name, $h_data, $extra_param);
}

/* Description:
 *   refer to html_yn_list()
 */
function html_yn_checkbox($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_yn_array_by_default_value($default_value);
	return html_checkbox($default_value, $name, $h_data, $extra_param);
}



// description:
//    refer to html_yn_list()
function html_status_list($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_status_array_by_default_value($default_value);
	return html_list($default_value, $name, $h_data, $extra_param);
}


// Description:
//   refer to html_yn_list()
function html_status_radio($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_status_array_by_default_value($default_value);
	return html_radio($default_value, $name, $h_data, $extra_param);
}

// Description:
//   refer to html_yn_list()
function html_status_label($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_status_array_by_default_value($default_value);
	return html_label($default_value, $name, $h_data, $extra_param);
}




// description:
//    refer to html_yn_list()
function html_gender_list($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gender_array_by_default_value($default_value);
	return html_list($default_value, $name, $h_data, $extra_param);
}


// Description:
//   refer to html_yn_list()
function html_gender_radio($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gender_array_by_default_value($default_value);
	return html_radio($default_value, $name, $h_data, $extra_param);
}

// Description:
//   refer to html_yn_list()
function html_gender_label($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gender_array_by_default_value($default_value);
	return html_label($default_value, $name, $h_data, $extra_param);
}






// description:
//    refer to html_yn_list()
function html_gendermore_list($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gendermore_array_by_default_value($default_value);
	return html_list($default_value, $name, $h_data, $extra_param);
}


// Description:
//   refer to html_yn_list()
function html_gendermore_radio($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gendermore_array_by_default_value($default_value);
	return html_radio($default_value, $name, $h_data, $extra_param);
}

// Description:
//   refer to html_yn_list()
function html_gendermore_label($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$h_data = _get_gendermore_array_by_default_value($default_value);
	return html_label($default_value, $name, $h_data, $extra_param);
}






function html_hidden($default_value, $name, $h_data_dummy=null, $extra_param=array()){
  $extra_attribute='';
  if (array_key_exists('id',         $extra_param)) 
    $extra_attribute = ' id="'.$extra_param['id'].'"';
	return "<input type=\"hidden\" name=\"$name\" value=\"$default_value\"$extra_attribute>";
}


// use checkbox as boolean display:
function html_boolean($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$extra_attribute='';
  if (array_key_exists('id',         $extra_param)) 
    $extra_attribute .= ' id="'.$extra_param['id'].'"';

  if ($default_value == 1){
  	return "<input type=\"checkbox\" name=\"$name\" value=\"1\" checked$extra_attribute>";
  }
  return "<input type=\"checkbox\" name=\"$name\" value=\"1\"$extra_attribute>";
}


# added by cliff on 2011/5/4
function html_asis($default_value, $name='', $h_data_dummy=null, $extra_param=array()){
	return $default_value;
}

/************************************************************
 component - text field
 ************************************************************/
// Description:
//   extra_param support '#SIZE#', '#MAXLENGTH#'
// 
function html_text($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$extra_attribute = '';
	
	if (is_null($extra_param)){
		// nothing to do
  } else {  	
  	if (array_key_exists('#SIZE#',      $extra_param))  $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MAXLENGTH#', $extra_param))  $extra_attribute .= ' maxlength="'.$extra_param['#MAXLENGTH#'].'"';
  	if (array_key_exists('id',         $extra_param))   $extra_attribute .= ' id="'.$extra_param['id'].'"';  }
  
	return "<input type=\"text\" name=\"$name\" value=\"$default_value\"$extra_attribute>";
}

// Descriptoin
//   same as html_text except type=password
function html_password($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$extra_attribute = '';
	if (is_null($extra_param)){
		// nothing to do
  } else {  	
  	if (array_key_exists('#SIZE#',      $extra_param))  $extra_attribute .= ' size="'.$extra_param['#SIZE#'].'"';
  	if (array_key_exists('#MAXLENGTH#', $extra_param))  $extra_attribute .= ' maxlength="'.$extra_param['#MAXLENGTH#'].'"';
  	if (array_key_exists('id',         $extra_param))   $extra_attribute .= ' id="'.$extra_param['id'].'"';  }
  
	return "<input type=\"password\" name=\"$name\" value=\"$default_value\"$extra_attribute>";
}

// Description:
//   extra_param support '#COLS#', '#ROWS#'
//
function html_textarea($default_value, $name, $h_data_dummy=null, $extra_param=array()){
	$extra_attribute = '';
	if (is_null($extra_param)){
		// nothing to do
  } else {  	
  	if (array_key_exists('#COLS#', $extra_param))  $extra_attribute .= ' cols="'.$extra_param['#COLS#'].'"';
  	if (array_key_exists('#ROWS#', $extra_param))  $extra_attribute .= ' rows="'.$extra_param['#ROWS#'].'"';
  	if (array_key_exists('id',     $extra_param))  $extra_attribute .= ' id="'.$extra_param['id'].'"';  }
  
	return "<textarea  name=\"$name\" $extra_attribute>$default_value</textarea>";
}


/************************************************************
 Text field related....
 ************************************************************/

function html_fix_edit_text($body){  
  #$body =~ s/"/&quot;/g;
  return preg_replace('/"/', '&quot;', $body);
}


function html_fix_edit_textarea($body){
  $body = preg_replace('/<textarea/i', '&lt;TEXTAREA', $body);
  $body = preg_replace('/<\/textarea>/', '&lt;/TEXTAREA&gt;', $body);
  #$body =~ s/<textarea/&lt;TEXTAREA/gi;
  #$body =~ s#</textarea>#&lt;/TEXTAREA&gt;#gi;
  return $body;
}

function html_fix_update_textarea($body){
  $body = preg_replace('/&lt;textarea/i', '<TEXTAREA', $body);
  $body = preg_replace('/&lt;/textarea&gt;/', '</TEXTAREA>', $body);
#	$body =~ s/&lt;textarea/<TEXTAREA/gi;
#	$body =~ s#&lt;/textarea&gt;#</TEXTAREA>#gi;
	return $body;
}

# remove some form element that is not used in preview but that will affect form submit
function html_fix_html_preview($body){
	$body = preg_replace('<\/?form[^>]*>', '', $body);
  $body = preg_replace('<input([^>]*)name="?[^>"]*/', '<input \1', $body);
	#$html =~ s/<\/?form[^>]*>//gi;
	#$html =~ s/<input([^>]*)name="?[^>"]*/<input \1/gi;
	return $html;
} 





####################################################
#
####################################################
function html_span($content, $h_param){
	return html_tag_span_div('span', $content, $h_param);
}

function html_div($content, $h_param){
	return html_tag_span_div('div', $content, $h_param);
}

function html_tag_span_div($tagname, $content, $h_param){
	$a_attribute = array();
	foreach ($h_param as $key => $value){
		array_push($a_attribute, "$key=\"$value\"");
	}
	if(count($a_attribute) > 0) array_unshift($a_attribute, '');
	$attribute = implode(' ', $a_attribute);
	
	return "<$tagname$attribute>$content</$tagname>";
}



/******************************************************************* 
 * 
 *******************************************************************/ 

// description
//   show <a href="url">something</a>
//   openwin : '' or not set => no open window. 1 (true): use target="_blank". 124x456: use javascript openwin with width 123 and height 456
function html_link($txt, $url, $h_param=array()){

  // check if each possibile optional parameter exists and initialize it.
  $openwin  = array_key_exists('openwin',   $h_param) ? $h_param['openwin'] : ''; 
  $css      = array_key_exists('css',       $h_param) ? $h_param['css']     : '';;
  $attribute= array_key_exists('attribute', $h_param) ? $h_param['attribute'] : '';
  
  
  if (preg_match("/x/", $openwin)){
    list ($oww, $owh) = explode('x', $openwin); # define the openwin size
  } else {
  	$oww = 0; // openwin width,
  	$owh = 0; // openwin height
  }
  
  if ($url == ''){ // no url, ignore openwin, owwh
    if (strcmp($css, '')==0){
    	return $txt; 
    } 
    // $attribute has ignored in this case
    return "<span class=\"$css\">$txt</span>";
  } 
  
  
  if (empty($openwin)){ // no open window
  	if (strcmp($css, '')==0){
      return "<a href=\"$url\" $attribute>$txt</a>";
    }
    return "<a href=\"$url\" class=\"$css\" $attribute>$txt</a>";
  } 
  
  if ($oww == 0 && $owh == 0){
  	if (strcmp($css, '')==0){
      return "<a href=\"$url\"  target=\"_blank\" $attribute>$txt</a>";
    }
    return "<a href=\"$url\" target=\"_blank\"  class=\"$css\" $attribute>$txt</a>";
  } 
  
  $openwin_js = openwin_js($url, $oww, $owh);
  if (strcmp($css, '')==0){
    return "<a href=\"javascript: void(0);\" onclick=\"$openwin_js\" $attribute>$txt</a>";
  }
  return "<a href=\"javascript: void(0);\" onclick=\"$openwin_js\" class=\"$css\" $attribute>$txt</a>";

}

function openwin_js($url, $width, $height, $name='', $toolbar=0, $resizable=1){
  $feature = "width=$width,height=$height,toolbar=$toolbar,resizable=$resizable";
  return "window.open('$url', '$name', '$feature');";
}



#
# size in "width"x"height
# e.g. 120x50
# if openwin == 1
# link will be target="_blank" if $owwh = '0x0'
# link will be openwin o.w. size in format of 760x400
function html_img($img, $url='', $ori_size='0x0', $new_size='0x0', $h_param=null){
  
  if (empty_string($ori_size)) $ori_size = '0x0';
  if (empty_string($new_size)) $new_size = '0x0';
  
  if (is_null($h_param)){
  	$h_param = array();
  }
  // check if each possibile optional parameter exists and initialize it.
  $openwin  = array_key_exists('openwin',   $h_param) ? $h_param['openwin'] : ''; 
  $css      = array_key_exists('css',       $h_param) ? $h_param['css']     : '';;
  $attribute= array_key_exists('attribute', $h_param) ? $h_param['attribute'] : '';

  if (preg_match("/x/", $openwin)){
    list ($oww, $owh) = explode('x', $openwin); # define the openwin size
  } else {
  	$oww = 0; // openwin width,
  	$owh = 0; // openwin height
  }
    

  $w = 0;
  $h = 0;
  #print STDERR "Original =$ori_size, new = $new_size. Resized = $w x $h"."\n";

  if (strcmp($new_size, '0x0') == 0){
    list ($w, $h) = explode('x', $ori_size);
  } elseif (strcmp($ori_size, '0x0')==0) {
    list ($w, $h) = explode('x', $new_size);
  } else {
    list ($dummy, $w, $h) = constraint_size($new_size, $ori_size);
  }

  #print STDERR "ori size: $ori_size, new: $new_size\n";

  if ($url == ''){
    if ($w == 0 && $h == 0){
      return "<img src=\"$img\" border=\"0\" $attribute />";
    } 
    return "<img src=\"$img\" width=\"$w\" height=\"$h\"  border=\"0\" $attribute />";  
  } 
  

  if (empty($openwin)){ // no open window
    if ($w == 0 && $h == 0){ // no image size specified
      return "<a href=\"$url\"><img src=\"$img\" border=\"0\" $attribute></a>";
    }
    
    return "<a href=\"$url\"><img src=\"$img\" border=\"0\" $attribute width=\"$w\" height=\"$h\"></a>";
  }
    
  
  if ($w == 0 && $h == 0){ // no image size specified
    if ($oww == 0 && $owh == 0){ 
      return "<a href=\"$url\" target=\"_blank\"><img src=\"$img\" border=\"0\" $attribute></a>";
    }
    $openwin_js = openwin_js($url, $oww, $owh); 
    return "<a href=\"javascript: void(0);\" onclick=\"$openwin_js\"><img src=\"$img\" border=\"0\" $attribute></a>";    
  } 
  
  
  if ($oww == 0 && $owh == 0){
    return "<a href=\"$url\" target=\"_blank\"><img src=\"$img\" border=\"0\" $attribute width=\"$w\" height=\"$h\"></a>";
  } 
  
  $openwin_js = openwin_js($url, $oww, $owh);
  return "<a href=\"javascript: void(0);\" onclick=\"$openwin_js\"><img src=\"$img\" border=\"0\" $attribute width=\"$w\" height=\"$h\"></a>";

}



// Description:
//    supporting function for html_img
// Return
//    ($flag, $w, $h)
//    $flag: 0 size not changed
//
function constraint_size($max_gemotery, $ori_size){	
  list ($width, $height) = explode('x', $max_gemotery);
  list ($old_w, $old_h)  = explode('x', $ori_size);

  if ($old_h == 0 || $height ==0){
    return array(0,0,0) ;
  }

  $new_w = 0;
  $new_h = 0;

  if ( $old_w/$old_h > $width/$height){
    if ($old_w > $width){
      $ratio = $old_w/$width;
      $new_w = $width;
      $new_h = floor($old_h / $ratio); // 	Returns the value of a number rounded downwards to the nearest integer, int() in perl
      return array(1, $new_w, $new_h);
    } else {
      return array(0, $old_w, $old_h);
    }
  } 
  
  if ($old_h > $height){
    $ratio = $old_h/$height;
    $new_h = $height;
    $new_w = floor($old_w / $ratio);
    return array(1, $new_w, $new_h);
  } else {
    return array(0, $old_w, $old_h);
  }
  
}

/* work with jquery UI 1.8, for CMS to show important message, some js is needed
 */
function html_dialog($title, $message){
return "<div id=\"dialog-modal\" title=\"$title\"><p>$message</p></div>";  
}


function create_html_db_lookup($default_value, $h_param=array()){

  if (is_null($h_param)){
  	$h_param = array();
  }
  // check if each possibile optional parameter exists and initialize it.
  $dbh_r          = array_key_exists('#DBH_R#',   $h_param) ? $h_param['#DBH_R#'] : ''; 
  $table_name     = array_key_exists('#TABLE_NAME#',   $h_param) ? $h_param['#TABLE_NAME#'] : ''; 
  $index_field    = array_key_exists('#INDEX_FIELD#',  $h_param) ? $h_param['#INDEX_FIELD#'] : '';;
  $value_field    = array_key_exists('#VALUE_FIELD#',  $h_param) ? $h_param['#VALUE_FIELD#'] : '';
  $where_condition= array_key_exists('#WHERE_CONDITION#',  $h_param) ? $h_param['#WHERE_CONDITION#'] : '';
	
	$h_data= array();

  if ($dbh_r){
	
	  $sqlstr = "select $index_field, $value_field from $table_name $where_condition";
	  if (! preg_match('/order/i', $where_condition)){
	    $sqlstr .= " order by $index_field" ;
	  }
	  //PDO  syntax  
	  $sth = $dbh_r->prepare($sqlstr);
	  $sth->execute();
	  while ($row = $sth->fetch(PDO::FETCH_NUM)){
	  	$h_data[$row[0]]=$row[1];
	  }
  }
	
	return $h_data;  
}

/* html_db_* function is added on 2011/11/13, instead of creating all value in lookup table, lookup those value directly from db
 * $h_data is not used, it generated from 
 */
function html_db_label($default_value, $name, $h_data, $extra_param=array()){
  $h_data = create_html_db_lookup($default_value, $extra_param);
  
  unset($extra_param['#DBH_R#']);
  unset($extra_param['#TABLE_NAME#']);
  unset($extra_param['#INDEX_FIELD#']);
  unset($extra_param['#VALUE_FIELD#']);
  unset($extra_param['#WHERE_CONDITION#']);

  if (count($h_data) > 0 ){
    return $this->html_label($default_value, $name, $h_data, $extra_param);
  }
  return $default_value;
}


function html_db_json($default_value, $name, $h_data, $extra_param=array()){
	$h_data = create_html_db_lookup($default_value, $extra_param);
  if (count($h_data) > 0 ){
  	$a_default_value = explode(',', $default_value);
  	
  	$h_default_value = array();
  	foreach ($a_default_value as $temp){
  		$h_default_value[$temp] = 1;
  	}
  	
  	
  	$for_tag  = array_key_exists('#FOR_TAG#',   $extra_param) ? $extra_param['#FOR_TAG#'] : ''; 
  	
  	if ($for_tag){
  		$a_result = array();
  		foreach ($h_data as $k => $v){
  			if ($h_default_value[$k] == 1){
  			  array_push($a_result, array('id'=> $k, 'name'=> $v));
  		  }
  		}
  		return json_encode($a_result);
  	}
    return json_encode($h_data);
  }
  return $default_value;	
}


?>